import Taro, { Component } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction, AtTimeline } from "taro-ui"
import { connect } from '@tarojs/redux'
import { getWindowHeight } from '@utils/style'
import { Empty } from '@components'
import * as actions from '@actions/order'
import classNames from 'classnames'
import empty from "@assets/order-empty.png"
import OrderCard from './order-card'
import './orderList.scss'

const PAGE_SIZE = 20

const tabList = [ '全部', '待付款', '待发货', '待收货', '已完成' ]

@connect(state => state.order, actions)
class OrderList extends Component {
  config = {
    navigationBarTitleText: '我的订单'
  }

  constructor (props) {
    super(props)
    const params = this.$router.params
    let type = 0
    if (params.type) {
      type = parseInt(params.type);
    }
    this.state = {
      showType: type,
      page: 1,
      orderList: [],
      hasMore: false,
      openLogistics: false,
      orderTrack: []
    }
  }

  componentDidMount() {
    this.loadOrderList(this.state.showType, 1)
  }

  handleSwitchTab (type) {
    this.setState({
      showType: type
    })
    this.loadOrderList(type, 1)
  }

  loadOrderList (type, page) {
    Taro.showLoading()
    const payload = {
      page: page,
      size: PAGE_SIZE,
      type: type
    }
    this.props.dispatchOrderList(payload).then((res) => {
      this.setState({
        orderList: page == 1 ? res.list : this.state.orderList.concat(res.list),
        page: page + 1,
        hasMore: res.hasMore
      })
      Taro.hideLoading()
    })
  }

  onLoadOrder() {
    if (this.state.hasMore) {
      this.loadOrderList(this.state.showType, this.state.page)
    }
  }

  handleCancel = (orderNo, type) => {
    Taro.showModal({
      title: '',
      content: '确定取消此订单？',
      confirmColor: '#E32D2F',
      cancelText: '取消',
      confirmText: '确定'
    }).then(res => {
      if (res.confirm) {
        Taro.showLoading()
        this.props.dispatchOrderCancel({orderNo: orderNo}).then(() => {
          Taro.hideLoading()
          this.handleSwitchTab(type)
        }).catch(() => {
          Taro.showToast({
            title: '订单取消失败',
            icon: 'none'
          })
        })
      }
    })
  }

  handlePay = (orderNo) => {
    this.props.dispatchOrderPay({orderNo: orderNo}).then(data => {
      const {order = {}, pay = {}} = data
      Taro.requestPayment(pay).then(res => {
        Taro.navigateTo({
          url: '/pages/payResult/payResult?msg=' + res.errMsg + '&orderNo=' + order.orderNo + '&payAmount=' + order.payAmount
        })
      }).catch((err) => {
        Taro.navigateTo({
          url: '/pages/payResult/payResult?msg=' + err.errMsg + '&orderNo=' + order.orderNo + '&payAmount=' + order.payAmount
        })
      })
    })
  }

  handleConfirm = (orderNo, type) => {
    Taro.showModal({
      title: '',
      content: '是否收到订单商品？',
      confirmColor: '#E32D2F',
      cancelText: '取消',
      confirmText: '确认'
    }).then(res => {
      if (res.confirm) {
        Taro.showLoading()
        this.props.dispatchOrderConfirm({orderNo: orderNo}).then(() => {
          Taro.hideLoading()
          this.handleSwitchTab(type)
        }).catch(() => {
          Taro.showToast({
            title: '订单确认失败',
            icon: 'none'
          })
        })
      }
    })
  }

  handleDelete = (orderNo, type) => {
    Taro.showModal({
      title: '',
      content: '确定删除此订单？',
      confirmColor: '#E32D2F',
      cancelText: '取消',
      confirmText: '确认'
    }).then(res => {
      if (res.confirm) {
        Taro.showLoading()
        this.props.dispatchOrderDelete({orderNo: orderNo}).then(() => {
          Taro.hideLoading()
          this.handleSwitchTab(type)
        }).catch(() => {
          Taro.showToast({
            title: '订单删除失败',
            icon: 'none'
          })
        })
      }
    })
  }

  handleLogistics = (orderNo) => {
    Taro.showLoading()
    this.props.dispatchOrderLogistics({orderNo: orderNo}).then( data => {
      let orderTrack = []
      data.trackList.map((item, index) => {
        const color = index === 0 ? 'red' : 'black'
        const icon = (index === 0 && data.isFinish) ? 'check-circle' : ''
        orderTrack.push({
          title: item.context, content: [item.time], color: color, icon: icon
        });
      })
      this.setState({ openLogistics: true, orderTrack: orderTrack})
      Taro.hideLoading()
    })
  }

  handleCloseLogistics = () => {
    this.setState({ openLogistics: false, orderTrack: []})
  }


  render () {
    const { showType, orderList, hasMore } = this.state
    const height = getWindowHeight(false)
  	return (
  	  <View className='order'>
        <View className='order-list__tab'>
          {tabList.map((item, index) => (
            <View
              key={'tab' + index}
              className='order-list-tab__item'
              onClick={this.handleSwitchTab.bind(this, index)}
            >
              <Text className={classNames('order-list-tab__item-txt', index === showType && 'order-list-tab__item-txt--active')}>{item}</Text>
              {index === showType &&
                <View className='order-list-tab__item-line' />
              }
            </View>
          ))}
        </View>
        {
          (!orderList || orderList.length == 0) ?
            <Empty image={empty} text='还没有任何订单呢' />
            :
            <ScrollView
              scrollY
              scrollTop='0'
              lowerThreshold='10'
              onScrolltolower={this.onLoadOrder.bind(this)}
              className='order-list__list'
              style={{ height }}
            >
              {orderList.map((order) => (
                <OrderCard
                  key={order.orderNo}
                  order={order}
                  type={showType}
                  onCancel={this.handleCancel}
                  onPay={this.handlePay}
                  onConfirm={this.handleConfirm}
                  onDelete={this.handleDelete}
                  onLogistics={this.handleLogistics}
                />
              ))}
              {!hasMore && <View className='no-more'>没有更多了～</View>}
            </ScrollView>
        }

        <AtModal
          isOpened={this.state.openLogistics}
          onClose={this.handleCloseLogistics}
        >
          <AtModalHeader>订单跟踪</AtModalHeader>
          <AtModalContent>
            <AtTimeline
              items={this.state.orderTrack}
            >
            </AtTimeline>
          </AtModalContent>
          <AtModalAction></AtModalAction>
        </AtModal>

  	  </View>
  	)
  }
}

export default OrderList
